/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

(function($){
    selectedKid = -1;
    editor = null;
    
    mafun = function(){
            var input = $(this);
            input.bind("click.thumb", function(){alert(1)})
        };
        
    loadKid = function(input, date, offset){
                
                
                //reset objects
                $(".calendarkids").css("display","none");
                $(".kidstoday").css("display","none");
                $("#kiddiaper").css("display","block");
                $("#kidnote").css("display","block");
                $("div.overview").css("display","block");
                $("div.edit").css("display","none");
                //read data
                var selectedIndex = input.attr("id").substring(4);
                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: {kidId: selectedIndex, date:date, offset:offset, action: "readKidForCreche"},
                    dataType: "xml",
                    success: function(data) {
                        //$('.result').html(data);
                        //remove info of other kids
                        $("#diaperstoday > .overview > table tr").remove();
                        $("#sleeptoday > .overview > table tr").remove();
                        $("#drinktoday > .overview > table tr").remove();
                        $("#foodtoday > .overview > table tr").remove();
                        $("#temperaturetoday > .overview > table tr").remove();


                        //set info of kid
                        //set name
                        $("#kidInfo .name").html($(data).find("kid").attr("firstname") + " " + $(data).find("kid").attr("name"));
                        $("#kidInfo .date").html(input.formatDateKey($(data).find("kid").attr("date")));
                        
                        //set prev and next on calendar
                        $("#kidInfo .datenavprev").unbind("click.prev");
                        $("#kidInfo .datenavprev").bind("click.prev", function() {loadKid(input, $(data).find("kid").attr("date"), -1);});
                        
                        $("#kidInfo .datenavnext").unbind("click.next");
                        $("#kidInfo .datenavnext").bind("click.next", function() {loadKid(input, $(data).find("kid").attr("date"), 1);});
                        
                        

                        //set in out
                        $("#kidInToday > .overview").html($(data).find("kid").attr("in"));
                        $("#kidOutToday > .overview").html($(data).find("kid").attr("out"));

                        $("#kiddate").html(input.formatDateKey($(data).find("kid").attr("date")));
                        selectedKid = $(data).find("kid").attr("id");

                        //set diaper info
                        $(data).find("diaper").each( function() {
                            $("<tr><td>"+$(this).attr("time") + "</td></tr>").appendTo("#diaperstoday > .overview > table");
                        });

                        //set sleep info
                        $(data).find("sleep").each( function() {

                            $("<tr><td class=\"from\">"+$(this).attr("sleepFrom") + "</td><td class=\"to\">"+$(this).attr("sleepTo")+"</td></tr>").appendTo("#sleeptoday > .overview > table");
                        });

                        //set drink info
                        $(data).find("drink").each( function() {
                            $("<tr><td>"+$(this).attr("timeFrom") + "</td><td>" + $(this).attr("timeTo") + "</td><td>" + $(this).attr("type") + "</td><td>" + $(this).attr("amount") + "cc</td></tr>").appendTo("#drinktoday > .overview > table");
                        });

                        //set food info
                        $(data).find("food").each( function() {
                            $("<tr><td>" + $(this).attr("timeFrom") + "</td><td>" + $(this).attr("timeTo") + "</td><td>" + $(this).attr("title") + "</td><td>" + $(this).attr("score") + "</td> </tr>").appendTo("#foodtoday > .overview > table");
                        });

                        //set in out
                         $(data).find("temperature").each( function() {
                            $("<tr><td>" + $(this).attr("time") + "</td><td>" + $(this).attr("degree") + "</td></tr>").appendTo("#temperaturetoday > .overview > table");
                        });

                    }
                }
                )
                
                 //set calendar
                var datetoday = new Date();
                input.loadCalendar(selectedIndex, datetoday.getYear()+1900, datetoday.getMonth()+1);

                //set next week calendar
                input.loadCalendarNextWeek(selectedIndex);

                //set text editor content.
                if(editor != null)
                    input.loadEditorNote(selectedIndex);
            };
    
    $.fn.extend({
        
        formatDateKey : function (key){
            var year = key.substring(0, 4);
            var month = key.substring(4, 6);
            var day = key.substring(6, 8);

            return day + "/" + month + "/" + year;
        },

        ma: mafun,
        
        initThumbs: function(){
            $(this).bind("click.thumb", function(){loadKid($(this), null, '0');});

        },
        loadCalendar : function(selectedIndex, yearToLoad, monthToLoad){
            $.ajax({
                url: 'calendar_actions.php',
                type: "POST",
                data: {kidId: selectedIndex, year: yearToLoad, month: monthToLoad, action: "readCalendarForKid"},
                dataType: "xml",
                success: function(data) {
                    $("#kidcalendarmonth .monthcalendar").remove();

                    var result = "<table class=\"monthcalendar\">";
                    var prevCalYear = yearToLoad;
                    var prevCalMonth = monthToLoad - 1;

                    var nextCalYear = yearToLoad;
                    var nextCalMonth = monthToLoad + 1;
                    if(monthToLoad == 1){
                        prevCalMonth = 12;
                        prevCalYear -= 1;
                    }else if (monthToLoad == 12) {
                        nextCalMonth = 1;
                        nextCalYear += 1;
                    }
                    result += "<tr><th><a href=\"javascript:loadCalendar("+selectedIndex+","+prevCalYear+","+prevCalMonth+")\">&lt;&lt;</a></th><th colspan=\"5\">"+$(data).find("calendarMonth").attr("monthLabel") + " " + $(data).find("calendarMonth").attr("year") +"</th><th><a href=\"javascript:loadCalendar("+selectedIndex+","+nextCalYear+","+nextCalMonth+")\">&gt;&gt;</a></th></tr>";
                    result += "<tr><th>Ma</th><th>Di</th><th>Wo</th><th>Do</th><th>Vr</th><th>Za</th><th>Zo</th></tr>";
                    result += "<tr>";

                    var index = 1;
                    $(data).find("calendarDayparts").each( function() {
                        var calDayClass = "open";
                        if($(this).attr("registeredDay") == "yes")
                            calDayClass = "registeredDay";
                        result += "<td id=\"c_"+ $(this).attr("date") +"\" class=\""+calDayClass + " " + $(this).attr("itemType") + "\">" + $(this).attr("date").substring(6) + "</td>";
                        if(index%7 == 0)
                            result += "</tr><tr>";
                        index++;
                    });
                    result += "</tr>";
                    result += "</table>";
                    $(result).appendTo("#kidcalendarmonth #calendar");

                    //set default start and stop
                    $("#fromTime").attr("value", ($(data).find("calendarMonth").attr("defaultStart")));
                    $("#toTime").attr("value", ($(data).find("calendarMonth").attr("defaultEnd")));

                    //loop again over xml to add hover
                    $(data).find("calendarDayparts").each( function() {
                        if($(this).attr("registeredDay") == "yes"){
                            $("#c_" + $(this).attr("date")).bind("mouseover", {me:$(this)}, 
                                function (event) { 
                                    var selectedDay = event.data.me.attr("date").substring(6);
                                    var html = "";
                                    $(event.data.me).find("daypart").each( function() {

                                        html += $(this).attr("startTime") + " --> " + $(this).attr("endTime") + "<br/>";
                                    });
                                    $("#selectedTime").html("op " +selectedDay + ": <br/> " + html);
                                    //$("#selectedTime").html("op " +selectedDay + ": <br/> " +event.data.me.attr("startTime") + " -> " + event.data.me.attr("endTime"));
                                });

                        }
                    });

                    //registere event listener to open days of this month
                    $("#kidcalendarmonth .open.this").click(function (){
                         $(this).addTimeToCalendar(this);
                    });

                    $("#kidcalendarmonth .registeredDay.this").click(function (){
                         $(this).addTimeToCalendar(this);
                    });


                }
            });
        },
        addTimeToCalendar: function (obj) {
    
            $.ajax({
                url: 'calendar_actions.php',
                type: "POST",
                data: {addtype:$('input:radio[name=addtype]:checked').val(), kidId: selectedKid, cDate: $(obj).attr("id").substring(2),  cStartTime: $("#fromTime").attr("value"), cEndTime: $("#toTime").attr("value"), action: "addTime"},
                dataType: "xml",
                success: function(data) {
                    //$('.result').html(data);
                    if($(data).find("result").attr("status") == "error"){
                        $(".errormsg").html($(data).find("error").attr("descr"));
                    }
                    else if($(data).find("result").attr("status") == "ok"){
                        //handle success
                        var date = $(data).find("calendar").attr("date");
                        $("#c_"+date).attr("class", "registered");

                        $(this).loadCalendarNextWeek(selectedKid);
                    }
                }
            });
        },
        loadCalendarNextWeek : function(selectedIndex){
            $.ajax({
                url: 'calendar_actions.php',
                type: "POST",
                data: {kidId: selectedIndex, numDays: 7, action: "readNextCalendarDaysForKid"},
                dataType: "xml",
                success: function(data) {
                     $("#weekcalendar .weekcalendar").remove();
                    var result = "<table class=\"weekcalendar\">";
                    result += "<tr><th>Volgende " + 7 + " dagen</th></tr>"
                    $(data).find("calendar").each( function() {

                        var timeString = "-";
                        if( $(this).attr("registeredDay") == "yes")
                            timeString = $(this).attr("startTime") + " --> " + $(this).attr("endTime");

                        result += "<tr><td>" + $(this).formatDateKey( $(this).attr("date")) + "</td><td>" + timeString + "</td></tr>";
                    });
                    result += "</table>";
                    $(result).appendTo("#weekcalendar");
                }
            });
        },
        loadEditorNote : function (selectedIndex) {
            $.ajax({
                url: 'kid_actions.php',
                type: "POST",
                data: {kidId: selectedIndex, action: "readNoteForKids"},
                dataType: "xml",
                success: function(data) {
                    editor.html($(data).find("report").text());
                }
            });
        },
        editable : function () {
            var input = $(this);
            input.bind("click.edit", function(){
            
                $(this).parent().parent().find(".time").attr("value", input.getTime());
                $(this).parent().parent().find(".overview").slideUp();
                //tab edit to slide down
               var tabindex = $(this).siblings("input[name='edittab']").attr("value");
               if(tabindex == null)
                   tabindex = "edit";
               else
                   tabindex = "tab"+tabindex;

                $(this).parent().parent().find("."+tabindex).slideDown();
            });
        },
        getTime : function () {
            var now = new Date();
            var hrs = now.getHours();
            if(hrs < 10)
                hrs =  "0" + hrs;
            var mins = now.getMinutes();
            if(mins < 10)
                mins = "0" + mins;
            var timeNow = hrs + ":" + mins;
            return timeNow;
        }, 
        kindEditor: function() {
            KindEditor.ready(function(K) {
                editor = K.create("#editor_note", {
                    langType : 'en'
                });
            });
        },
        addInTime: function () {
            var input = $(this);
            input.bind("click.edit", function(){
                $("#kidInOut div.edit").slideUp();
                $("#kidInOut .overview").slideDown();

                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: {kidId: selectedKid, inTime: $("#inTime").attr("value"), action: "saveTimeIn"},
                    dataType: "xml",
                    success: function(data) {
                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success
                            var time = $(data).find("kidInOut").attr("inTime");
                            $("#kidInToday > .overview ").html(time);
                        }
                    }
                });
            });
        },
        addOutTime: function() {
            var input = $(this);
            input.bind("click.edit", function(){
                $("#kidInOut div.edit").slideUp();
                $("#kidInOut .overview").slideDown();

                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: {kidId: selectedKid, outTime: $("#outTime").attr("value"), action: "saveTimeOut"},
                    dataType: "xml",
                    success: function(data) {
                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success
                            var time = $(data).find("kidInOut").attr("outTime");
                            $("#kidOutToday > .overview ").html(time);
                        }        
                    }
                });
            })
        },
        addTemperature: function() {
          var input = $(this);
          input.bind("click.edit", function() {
              $("#kidtemperature div.edit").slideUp();
              $("#kidtemperature .overview").slideDown();

              $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: {kidId: selectedKid, tDegree:$("#temperaturedegree").attr("value"), tTimestamp: $("#temperaturetime").attr("value"), action: "addTemperature"},
                    dataType: "xml",
                    success: function(data) {
                        //$('.result').html(data);

                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success
                            var time = $(data).find("temperature").attr("time");
                            var degree  = $(data).find("temperature").attr("degree");
                            $("<tr><td>"+ time + "</td><td>"+degree+"</td></tr>").appendTo("#temperaturetoday > .overview > table");
                        }
                    }
              });
          })
        },
        addDiaper: function(){
            var input = $(this);
            input.bind("click.edit", function(){
                $("#kiddiaper div.edit").slideUp();
                $("#kiddiaper .overview").slideDown();

                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: {kidId: selectedKid, dType: 1, dTimestamp: $("#diapertime").attr("value"), action: "addDiaper"},
                    dataType: "xml",
                    success: function(data) {
                        //$('.result').html(data);

                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success
                            var time = $(data).find("diapers").attr("time");
                            $("<tr><td>"+ time + "</td></tr>").appendTo("#diaperstoday > .overview > table");
                        }
                    }
                });
            })
        },
        addDrink: function(step){
            var input = $(this);
            input.bind("click.edit", {step: step}, function(){
                $("#kiddrink div.edit").slideUp();
                $("#kiddrink .overview").slideDown();

                var params = null;
                if(step == 'from'){
                    params = {kidId: selectedKid, lTimestamp: $("#drinktimefrom").attr("value"), lType: $("#drinktype").attr("value"), action: "addDrinkFrom"};
                }
                else if(step == 'to'){
                    params = {kidId: selectedKid, lTimestamp: $("#drinktimeto").attr("value"), lAmount: $("#drinkamount").attr("value"), action: "addDrinkTo"};
                }

                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: params,
                    dataType: "xml",
                    success: function(data) {
                        //$('.result').html(data);
                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success
                            var timeFrom = $(data).find("drink").attr("timeFrom");
                            var timeTo = $(data).find("drink").attr("timeTo");
                            var type = $(data).find("drink").attr("drinkTypeString");
                            var amount = $(data).find("drink").attr("amount");
                            var begin = $(data).find("drink").attr("begin");
                            if(begin == "yes"){
                                $("<tr><td>"+timeFrom + "</td><td class=\"to\">...</td><td>" + type + "</td><td class=\"amount\"></td></tr>").appendTo("#drinktoday > .overview > table");
                                $("#drinkimage input[name='edittab']").attr("value", "2");
                            }
                            else{
                                $("#drinktoday  td.to").each(function () {
                                    if($(this).text() == "..."){
                                        $(this).text(timeTo);

                                    }
                                });
                                $("#drinktoday  td.amount").each(function () {
                                     if($(this).text() == ""){
                                        $(this).text(amount);
                                     }
                                });
                                $("#drinkimage input[name='edittab']").attr("value", "1");                    
                            }

                        }
                    }
                });

            })
        },
        addFood: function(step) {
            var input = $(this);
            input.bind("click.edit", {step: step}, function(event){
                
                $("#kidfood div.edit").slideUp();
                $("#kidfood .overview").slideDown();

                //set post parameters
                var params = null;
                if(step == "from")
                    params = {kidId: selectedKid, fTimestamp: $("#foodtimefrom").attr("value"), fMenu: $("#foodmenu").attr("value"), action: "addFoodFrom"};
                else if(step == "to")
                    params = {kidId: selectedKid, fTimestamp: $("#foodtimeto").attr("value"), fScore: $("#foodscore").raty('score'), action: "addFoodTo"};


                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: params,
                    dataType: "xml",
                    success: function(data) {
                        //$('.result').html(data);
                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success
                            var timeFrom = $(data).find("food").attr("timeFrom");
                            var timeTo = $(data).find("food").attr("timeTo");
                            var menu = $(data).find("food").attr("recipeString");
                            var score = $(data).find("food").attr("score");
                            var begin = $(data).find("food").attr("begin");
                            if(begin == "yes"){
                                $("<tr><td>" + timeFrom + "</td><td class=\"to\">...</td><td>" + menu + "</td><td class=\"score\"></td></tr>").appendTo("#foodtoday > .overview > table");
                                $("#foodimage input[name='edittab']").attr("value", "2");

                            }else {
                                $("#foodtoday  td.to").each(function () {
                                    if($(this).text() == "..."){
                                        $(this).text(timeTo);

                                    }
                                });
                                $("#foodtoday  td.score").each(function () {
                                     if($(this).text() == ""){
                                        $(this).text(score);
                                     }
                                });
                                $("#foodimage input[name='edittab']").attr("value", "1");
                            }
                        }
                    }
                });
            })
        },
        addSleep: function(step) {
            var input = $(this);
            input.bind("click.edit", {step: step}, function(event){
                $("#kidsleep div.edit").slideUp();
                $("#kidsleep .overview").slideDown();
                //set post parameters
                var params = null;
                if(step == "from")
                    params = {kidId: selectedKid, sTimestamp: $("#sleeptimefrom").attr("value"), action: "addSleepFrom"};
                else if(step == "to")
                    params = {kidId: selectedKid, sTimestamp: $("#sleeptimeto").attr("value"), action: "addSleepTo"};

                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: params,
                    dataType: "xml",
                    success: function(data) {
                        //$('.result').html(data);
                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success
                            var timeFrom = $(data).find("sleep").attr("timeFrom");
                            var timeTo = $(data).find("sleep").attr("timeTo");
                            var begin = $(data).find("sleep").attr("begin");
                            if(begin == "yes"){
                                $("<tr><td class=\"from\">"+ timeFrom + "</td><td class=\"to\">"+"..."+"</td></tr>").appendTo("#sleeptoday > .overview > table");
                                //set tabindex to 2
                                 $("#sleepimage input[name='edittab']").attr("value", "2");

                            } else {
                                $("#sleeptoday  td.to").each(function () {
                                    if($(this).text() == "..."){
                                        $(this).text(timeTo);

                                    }
                                });
                                //set tabindex back to 1
                                $("#sleepimage input[name='edittab']").attr("value", "1");
                            }
                        }
                    }
                });
            });
        },
        saveNote: function() {
         var input = $(this);
            input.bind("click.edit", function(event){
                $.ajax({
                    url: 'kid_actions.php',
                    type: "POST",
                    data: {kidId: selectedKid, notedata: editor.html(), action: "saveNote"},
                    dataType: "xml",
                    success: function(data) {
                        //$('.result').html(data);
                        if($(data).find("result").attr("status") == "error"){
                            $(".errormsg").html($(data).find("error").attr("descr"));
                        }
                        else if($(data).find("result").attr("status") == "ok"){
                            //handle success

                        }
                    }
                });

            })   
        }

        



        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    });
    
})(jQuery);


 $(document).ready(function() {
                //if clicked on a child thumb, load settings for kid
                $(".kidthumbtile").initThumbs();
                //init admin panels that have an edit function
                $("img.edit").editable();
                
                //add rating
                //ratings
                $('#foodscore').raty({
                    path: "/ukkepuk/source/html/css/images/",
                    half: true,
                    hintList:		['heel slecht', 'slecht', 'gemiddeld', 'goed', 'zeer goed']
                });

                //in out
                $("#kidInOut #kidInToday  .edit .add").addInTime();
                $("#kidInOut #kidOutToday .edit .add").addOutTime();
                //food
                $("#kidfood #foodtoday .tab1 .add").addFood('from');
                $("#kidfood #foodtoday .tab2 .add").addFood('to');
                //diaper
                $("#kiddiaper #diaperstoday .edit .add").addDiaper();
                //drink
                $("#kiddrink #drinktoday .tab1 .add").addDrink('from');
                $("#kiddrink #drinktoday .tab2 .add").addDrink('to');
                //sleep
                $("#kidsleep #sleeptoday .tab1 .add").addSleep('from');
                $("#kidsleep #sleeptoday .tab2 .add").addSleep('to');
                //savenote
                $("#kidnote .add").saveNote();
                //save temperature
                $("#kidtemperature #temperaturetoday .edit .add").addTemperature();
                //test
                $("#ma").ma();
                
                //init kind editor
                $("#editor_note").kindEditor();
            });